import { reqlogin } from "../../http/api"
import { Toast } from "antd-mobile"

//初始值
const initState={
    user:{
        phone:"",
        password:""
    },
    userInfo:sessionStorage.getItem("suerInfo")?JSON.parse(sessionStorage.getItem("suerInfo")):{}
}

//types 
const TYPES={
    LOGIN_CHANGE_USER:"LOGIN_CHANGE_USER",
    LOGIN_CHANGE_USERINFO:"LOGIN_CHANGE_USERINFO"
}

//修改state的reducer
const reducer=(state=initState,action)=>{
    switch(action.type){
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
        case TYPES.LOGIN_CHANGE_USERINFO:
            return {
                ...state,
                userInfo:action.userInfo
            }
        default:
            return state
    }
}

//actionCreators 
export const actions={
    changeUser:(key,value)=>({
        type:TYPES.LOGIN_CHANGE_USER,
        key,
        value
    }),
    //修改userInfo
    changeUserInfo:(userInfo)=>{
        //同步到本地存储
        if(userInfo.token){
            sessionStorage.setItem("userInfo",JSON.stringify(userInfo))
        }else{
            sessionStorage.removeItem("userInfo")
        }
        return {
            type:TYPES.LOGIN_CHANGE_USERINFO,
            userInfo
        }
    },
    //点击登录逻辑
    reqLogin:(push)=>{
        return (dispatch,getState)=>{
            let {
                login:{
                    user
                }
            } = getState();
            // 登录的请求
            reqlogin(user).then(res=>{
                Toast.show({
                    icon: 'success',
                    content: '登录成功',
                });
                dispatch(actions.changeUserInfo(res.data.list));
                push("/index/home");
            })
        }
    },
    //个人中心逻辑
    //点击退出
    exit:(push)=>{
        return (dispatch,getState)=>{
            dispatch(actions.changeUserInfo({}));
            push("/login")
        }
    }
}

//导出数据
export const getUser = state =>state.login.user
export const getUserInfo = state=>state.login.userInfo;

//导出reducer 
export default reducer